package com.qq.first_project.controller.page;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qq.first_project.common.R;
import com.qq.first_project.entity.Blog;
import com.qq.first_project.entity.User;
import com.qq.first_project.entity.vo.FirstPageBlogVo;
import com.qq.first_project.entity.vo.ShowBlogVo;
import com.qq.first_project.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin //跨域
@RequestMapping("/page/index")
public class IndexController {
    @Autowired
    private BlogService blogService;

    //分页查询所有博客列表
    @GetMapping("/list")
    R allList(@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum, @RequestParam(defaultValue = "10",value = "pageSize") Integer pageSize){
        Page<FirstPageBlogVo> pageInfo = new Page<>(pageNum,pageSize);
        Page page = blogService.getAllFirstPageBlog(pageInfo);
        return R.ok().data("data",page);
    }

    //查询最新四条推荐博客列表
    @GetMapping("/recommend")
    R recommendList(){
        List<FirstPageBlogVo> recommendedBlog  = blogService.getRecommendedBlog();
        return R.ok().data("data",recommendedBlog);
    }

    //搜索标题或内容中包含该字符串的博客
    @GetMapping("/search")
    R search(ModelMap modelMap, @RequestParam("key") String query) {
        List<FirstPageBlogVo> searchBlog = blogService.getSearchBlog(query);

        modelMap.addAttribute("blogs", searchBlog);
        modelMap.addAttribute("query", query);
        return R.ok().data("data",modelMap);
    }

    //博客信息统计
    @GetMapping("/footer/blogmessage")
    R blogMessage(ModelMap modelMap){
        int blogTotal = blogService.getBlogTotal();
        int blogViewTotal = blogService.getBlogViewTotal();
        int blogCommentTotal = blogService.getBlogCommentTotal();
        int blogMessageTotal = blogService.getBlogMessageTotal();

        modelMap.addAttribute("blogTotal",blogTotal);
        modelMap.addAttribute("blogViewTotal",blogViewTotal);
        modelMap.addAttribute("blogCommentTotal",blogCommentTotal);
        modelMap.addAttribute("blogMessageTotal",blogMessageTotal);
        return R.ok().data("data",modelMap);
    }

    //更新博客浏览量
    @PostMapping("/updateViews")
    R updateViews(Long id, Integer views){
        ShowBlogVo showBlogVo = blogService.getBlogById(id);
        showBlogVo.setViews(views + 1);
        int result = blogService.updateBlog(showBlogVo);
        if (result!=0) {
            return R.ok().message("修改成功");
        } else {
            return R.error().message("数据不存在");
        }

    }
}
